<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { queryHoldShare } from '@/api/front/fund/fundDataContent'

export default {
  name: 'SharesPosition',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    codeNumber: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null,
      legendData: [],
      seriesData: []
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      // 查询
      queryHoldShare(this.codeNumber).then(res => {
        // String转JSONArray
        const holdContentList = JSON.parse(res.content[0].holdContent)
        this.legendData = holdContentList.map(item => { return item.codeName })
        if (this.legendData.length === 0) return

        this.seriesData = holdContentList.map(item => { return { name: item.codeName, value: Number(item.percent) } })

        console.log('holdContentList', this.seriesData)

        this.chart.setOption({
          tooltip: {
            trigger: 'item',
            // formatter: '{a} <br/>{b} : {c}% ({d}%)'
            formatter: '{a} <br/>{b} : {c}%'
          },
          legend: {
            left: 'center',
            bottom: '10',
            data: this.legentData
          },
          calculable: true,
          series: [
            {
              name: '股票持仓',
              type: 'pie',
              roseType: 'radius',
              radius: [15, 95],
              center: ['50%', '38%'],
              data: this.seriesData,
              animationEasing: 'cubicInOut',
              animationDuration: 1000
            }
          ]
        })
      })
    }
  }
}
</script>
